package com.vivachek.protocol.converts

import com.vivachek.protocol.BaseResult
import com.vivachek.protocol.Parse.unit
import com.vivachek.protocol.enums.*
import com.vivachek.protocol.utils.ResultUtil

/**
 * @Author: YCB
 * @Time: 2022/9/29 11:30:06
 * @Email: congbin.yuan@vivachek.com
 * @Description: 设备状态解析类
 */
private const val COMMAND = 18
private const val EXPAND_CODE = 102
private const val LENGTH = 5

internal class StatusConvert : DataConvert(COMMAND, EXPAND_CODE, LENGTH) {

    override fun parse(data: List<Int>,origin:List<Int>) {
        when (val status = TestStatusEnums.convert(data.first())) {
            TestStatusEnums.LAST_TEST_RESULT -> {
                // ignore
            }
            TestStatusEnums.RESULT_GLUCOSE -> {
                var result = data[1] * 100f + data[2]
                val value = if (unit == UnitEnums.MMOL) {
                    result /= 10f
                    ResultUtil.convert(result)
                } else {
                    result.toInt().toString()
                }
                val sample = SampleEnums.convert(data[3])
                listener?.result(BaseResult.Glucose(value, unit, null, Flag.NONE, sample))
            }
            TestStatusEnums.KETONES_RESULT -> {
                val result = ResultUtil.convert((data[1] * 100f + data[2]) / 100)
                val sample = SampleEnums.convert(data[3])
                listener?.result(BaseResult.Ketones(result, UnitEnums.MMOL, null, Flag.NONE, sample))
            }
            TestStatusEnums.URIC_ACID_RESULT -> {
                val result = ResultUtil.convert(data[1] * 100f + data[2])
                val sample = SampleEnums.convert(data[3])
                listener?.result(BaseResult.UricAcid(result, UnitEnums.UMOL, null, Flag.NONE, sample))
            }
            TestStatusEnums.WARN_WRAPPER -> listener?.warn(WarnCodeEnums.convert(data.last()))

            TestStatusEnums.INSERT_TEST_PAPER,
            TestStatusEnums.WAIT_ADD_SAMPLE,
            TestStatusEnums.SAMPLE_ADDED,
            TestStatusEnums.KETONES_INSERT_STRIP,
            TestStatusEnums.KETONES_SELF_CHECK,
            TestStatusEnums.KETONES_SAMPLE_ADDED,
            TestStatusEnums.URIC_ACID_INSERT_STRIP,
            TestStatusEnums.URIC_ACID_SELF_CHECK,
            TestStatusEnums.URIC_ACID_SAMPLE_ADDED,
            TestStatusEnums.CODE_CHIP_INSERT_STRIP,
            TestStatusEnums.CODE_CHIP_FINISHED -> listener?.status(status)
        }

        listener?.needReply()
    }
}